"use strict";

/**
 * https://my.oschina.net/isgaoyi/blog/4717508 - v1.0 (2020-11-15T01:46:32+0800)
 * Copyright 2020 gaoyia@qq.com
 *
 * 修复四舍五入精度问题
 * @method Number.toFixed()
 * @param {int} param 需要保留的精度
 * @param {int} rejection=4 四舍五入的4，改成3就变成3舍4入
 * @return {string} 返回值
 */
Number.prototype.toFixed = function (Length, Rejection = 4) {
    const length = ~~Length; //取整
    const rejection = ~~Rejection; //取整
    if (length < 0 || length > 100) {
        throw new Error(
            "RangeError: toFixed() digits argument[0] must be between 0 and 100"
        );
    }
    if (rejection < 0 || rejection > 10) {
        throw new Error(
            "RangeError: toFixed() digits argument[1] must be between 0 and 10"
        );
    }
    let tStr = this.toString(),
        index = tStr.indexOf("."),
        arr = [tStr.slice(0, index)],
        res;
    if (index !== -1) {
        arr[1] = tStr.slice(index + 1, tStr.length);
    }
    if (this > Number.MAX_SAFE_INTEGER) {
        return Number(arr[0]).toExponential();
    }
    if (arr.length <= 1) {
        res = this.toString();
    } else {
        if (arr[1][length] > rejection) {
            // 截断到需要入的后一位
            arr[1] = arr[1].slice(0, length + 1);
            if (length === 0) {
                arr[0] = (Number(arr[0]) + 1).toString();
            } else {
                // 获取小数位前面有多少个0
                let zero = /^0+/.exec(arr[1]);
                zero = zero ? zero[0] : "";
                // 截断后加一
                arr[1] = arr[1].slice(0, length);
                // 记录原始长度
                const before = Number(arr[1]).toString();
                const later = (Number(arr[1]) + 1).toString();
                // 如果发生整体进位
                if (later.length > before.length || Number(arr[1]) === 0) {
                    if (zero.length === 0) {
                        // 整数位加1，小数位去掉最高位
                        arr[0] = Number(arr[0]) + 1;
                        arr[1] = later.slice(1, arr[1].length + 1);
                    } else {
                        // 将0字符的长度减小1
                        zero = zero.slice(0, zero.length - 1);
                        arr[1] = later;
                    }
                } else {
                    // 没有发生整体进位,直接计算小数位
                    arr[1] = later;
                }
                arr[1] = zero + arr[1];
            }
        } else {
            // 直接截断
            arr[1] = arr[1].slice(0, length);
        }
        res = length === 0 ? arr[0] : arr[0] + "." + arr[1];
    }
    // 补全多余的0
    if (arr[1] && arr[1].length < length) {
        for (let i = 0; i < length - arr[1].length; i++) res += "0";
    } else if (!arr[1] && length !== 0) {
        res += ".";
        for (let i = 0; i < length; i++) res += "0";
    }
    return res;
};